﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using ICSharpCode.TextEditor;
//using ICSharpCode.TextEditor.Document;

namespace Nizm0.QOT.Forms
{
    public class ChildWindow : Library.Forms.MyMdiChild
    {
        //ICSharpCode.TextEditor.TextEditorControl editor;
        ICSharpCode.AvalonEdit.TextEditor editor;

        private System.Windows.Forms.Integration.ElementHost elementHost;

        public ChildWindow(string file, Form parent)
            : base(ref parent)
        {
            InitializeComponent();

            editor = AddNewTextEditor(System.IO.Path.GetFileName(file));
            try
            {
                editor.Load(file);
                string[] extensions = { ".sql", "sql" };
                ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.RegisterHighlighting("SQL", extensions, ChildWindow.LoadHighlightingDefinition("Nizm0.QOT.Resources.SQL-Mode.xshd"));
                editor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance.GetDefinitionByExtension(System.IO.Path.GetExtension(file));
                // Modified flag is set during loading because the document 
                // "changes" (from nothing to something). So, clear it again.
                SetModifiedFlag(editor, false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name);
                return;
            }
            this.Text = file;//editor.FileName;
            //this.Show();
        }

        public ChildWindow(Library.Objects.ProcedureFromDatabase procedure, Form parent)
            : base(ref parent)
        {
            InitializeComponent();

            editor = AddNewTextEditor(procedure.Name);
            try
            {
                editor.Text = procedure.Text;
                //System.IO.Stream str = new System.IO.FileStream(@"C:\Users\Nizm0\Documents\Visual Studio 2010\Projects\QOT\Nizm0.QOT.Program\Resources\SQL-Mode.xshd", System.IO.FileMode.Open, System.IO.FileAccess.Read);

                    //C:\Users\Nizm0\Documents\Visual Studio 2010\Projects\QOT\Nizm0.QOT.Program\Resources\SQL-Mode.xshd
                editor.SyntaxHighlighting = ChildWindow.LoadHighlightingDefinition("Nizm0.QOT.Resources.SQL-Mode.xshd");
                //editor.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(editor.Options); // .SetHighlighting("SQL");
                // Modified flag is set during loading because the document 
                // "changes" (from nothing to something). So, clear it again.
                SetModifiedFlag(editor, false);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name);
                return;
            }
            this.Text = "[" + ((Library.Objects.Server)((Library.Objects.DataBase)procedure.Parent).Parent).Name + "].[" + ((Library.Objects.DataBase)procedure.Parent).Name + "].dbo.[" + procedure.Name + "]";
            //this.Show();
        }

        public ChildWindow(string text, string name, Form parent)
            : base(ref parent)
        {
            InitializeComponent();

            editor = AddNewTextEditor(name);
            try
            {
                editor.Text = text;

                //System.IO.Stream str = new System.IO.FileStream(FileHighlingDefinition, System.IO.FileMode.Open, System.IO.FileAccess.Read);

                editor.SyntaxHighlighting = Settings.Instance.TextHighlighting;


                SetModifiedFlag(editor, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().Name);
                return;
            }
            this.Text = name;
            //this.Show();
        }

        public ChildWindow(System.Windows.UIElement control, Form parent)
            : base(ref parent)
        {
            InitializeComponent();
            elementHost.Child = control;
        }

        public ChildWindow(System.Windows.Forms.Form control, Form parent)
            : base(ref parent)
        {
            InitializeComponent();
            editor = null;
            this.Controls.Remove(elementHost);
            //control.Parent = parent;
            //control.MdiParent = parent;
            control.TopLevel = false;
            this.Controls.Add(control);
        }

        public ChildWindow(System.Windows.Forms.Control control)
            : base()
        {
            InitializeComponent();
            editor = null;
            this.Controls.Remove(elementHost);
            control.Dock = DockStyle.Fill;
            this.Text = "List";
            this.Controls.Add(control);
        }

        private bool IsModified(ICSharpCode.AvalonEdit.TextEditor editor)
        {
            // TextEditorControl doesn't seem to contain its own 'modified' flag, so 
            // instead we'll treat the "*" on the filename as the modified flag.
            return editor.IsModified;//.Parent.Text.EndsWith("*");
        }

        private void SetModifiedFlag(ICSharpCode.AvalonEdit.TextEditor editor, bool flag)
        {
            //if (IsModified(editor) != flag)
            //{
            //    var p = editor.Parent;
            //    if (IsModified(editor))
            //        p.Text = p.Text.Substring(0, p.Text.Length - 1);
            //    else
            //        p.Text += "*";
            //}
        }
        public static ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition LoadHighlightingDefinition(string resourceName)//, ICSharpCode.AvalonEdit.TextEditor editor
        {
            ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition highlightingDefinition;
            try
            {
                //var type = typeof(Windows.ApplicationModel.ResourceLoader);
                //var fullName = type.Namespace + "." + resourceName;
                //using (var stream = type.Assembly.GetManifestResourceStream(fullName))
                //using (var reader = new System.Xml.XmlTextReader(stream))
                //    return ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);

                System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                
                using (System.IO.Stream s = assembly.GetManifestResourceStream(resourceName))
                {
                    using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(s))
                    {
                        highlightingDefinition = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
                    }
                }
                return highlightingDefinition;
            }
            catch
            {
                return null;
            }
        }

        public static ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition LoadHighlightingDefinition(System.IO.Stream stream)//, ICSharpCode.AvalonEdit.TextEditor editor
        {
            ICSharpCode.AvalonEdit.Highlighting.IHighlightingDefinition highlightingDefinition;
            try
            {
                using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream))
                {
                    highlightingDefinition = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
                }
                return highlightingDefinition;
            }
            catch
            {
                return null;
            }
        }

        private ICSharpCode.AvalonEdit.TextEditor AddNewTextEditor(string title)
        {
            //var tab = new TabPage(title);
            
            var editor = new ICSharpCode.AvalonEdit.TextEditor();//.TextEditorControl();
            

            this.elementHost.Child = editor;
            editor.SyntaxHighlighting = ChildWindow.LoadHighlightingDefinition("Nizm0.QOT.Resources.SQL-Mode.xshd");
            return editor;
        }

        #region Initialize Components

        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.elementHost = new System.Windows.Forms.Integration.ElementHost();
            this.SuspendLayout();
            // 
            // elementHost
            // 
            this.elementHost.Dock = System.Windows.Forms.DockStyle.Fill;
            this.elementHost.Location = new System.Drawing.Point(0, 0);
            this.elementHost.Name = "elementHost";
            this.elementHost.Size = new System.Drawing.Size(284, 264);
            this.elementHost.TabIndex = 0;
            this.elementHost.Text = "elementHost";
            this.elementHost.Child = null;
            // 
            // ChildWindow
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 264);
            this.Controls.Add(this.elementHost);
            this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            this.Name = "ChildWindow";
            this.ResumeLayout(false);

        }

        #endregion 
        #endregion
    }
}
